<?php

namespace app\api\controller;

use app\api\model\Eggs as EggsDB;
use app\api\model\GameBowl as GameBowlDB;
use app\api\model\Game2Players as Game2PlayersDB;
use app\api\model\Game2PlayersSum as Game2PlayersSumDB;
use app\api\model\UserUseEggs as UserUseEggsDB;
use app\api\model\Wallets as WalletsDB;
use Illuminate\Support\Carbon;
use support\Request;
use app\api\model\Game2 as Game2DB;
use app\api\model\Game2Puke as Game2PukeDB;


class Game2Controller
{
    //添加猫狗斗游戏
    public function add()
    {
        $req = [];
        $per = Game2DB::orderBy('id', 'desc')->first();
        if ($per == null || $per['times'] == 122) {
            $req['date_id'] = date("YmdHis");
            $req['times'] = 1;
            $req['created_at'] = Carbon::now()->toDateTimeString();
            $req['stop_time'] = Carbon::now()->addSeconds(20)->toDateTimeString();
            $req['open_time'] = Carbon::now()->addSeconds(25)->toDateTimeString();
            //清除棋牌数据库
            Game2PukeDB::where('used', '!=', 0)->update(['used' => 0]);
        } else {
            $req['date_id'] = $per['date_id'];
            $req['times'] = $per['times'] + 1;
            $req['created_at'] = Carbon::now()->toDateTimeString();
            $req['stop_time'] = Carbon::now()->addSeconds(20)->toDateTimeString();
            $req['open_time'] = Carbon::now()->addSeconds(25)->toDateTimeString();
        }
        $res = Game2DB::insertGetId($req);
        return json([
            'code' => 0,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    //获取游戏列表
    public function list()
    {
        $res = Game2DB::orderBy('id', 'desc')->paginate(10);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    //获取某期号的游戏历史记录
    public function getDateIdList(Request $request)
    {
        $date_id = $request->get('date_id');
        $res = Game2DB::where('date_id', $date_id)->get();
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    //投注
    public function playGame(Request $request)
    {

        $req = [];
        //获取用户id
        $uid = $request->uid;
        $req['user_id'] = $uid;
        $req['count'] = $request->post('count');
        /**
         * AA猫赢  BB狗赢  AB 和局 A猫单赢 B狗单赢   A2猫双赢  B2狗双赢
         */
        $req['type'] = $request->post('type');
        $req['rate'] = $request->post('rate');

        $req['created_at'] = Carbon::now()->toDateTimeString();
        $id = $request->post('id');

        //判断是否暂停投注
        $r = Game2DB::where('id', $id)->first();

        $req['date_id'] = $r['date_id'];
        $req['times'] = $r['times'];
        $req['game_id'] = $id;
        $stop_time = Carbon::createFromFormat('Y-m-d H:i:s', $r['stop_time']);
        $now_time = Carbon::now();
        if ($now_time->gte($stop_time)) {
            return json([
                'code' => 0,
                'msg' => 'ok',
                'data' => '已经暂停竞猜',
            ]);
        }
        $count_db = WalletsDB::where('wallet_user_id', $uid)->value("held_eggs");
        if ($req['count'] <= $count_db) {
            $res = Game2PlayersDB::insertGetId($req);
            WalletsDB::where('wallet_user_id', $uid)->update([
                "held_eggs" => $count_db - $req['count'],
                "used_eggs" => WalletsDB::where('wallet_user_id', $uid)->value("used_eggs") + $req['count']
            ]);
//            UserUseEggsDB::insertGetId([
//                'user_id' => $uid,
//                'count' => $req['count'],
//                'use_type' => '游戏-猫狗斗-投注',
//                'type' => 0,
//                'created_at' => Carbon::now()->toDateTimeString()
//            ]);
            //添加U蛋记录
            EggsDB::insertGetId([
                'uid' => $uid,
                'count' => $req['count'],
                'type' => '游戏-竞猜-猫狗斗' . $r['date_id'] . '-' . $r['times'],
                'yu_e' => $count_db - $req['count'],
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
            //生成聚合信息
            $doesntExist = Game2PlayersSumDB::where('date_id', $r['date_id'])->where('times', $r['times'])->where('user_id', $uid)->doesntExist();
            if ($doesntExist) {
                Game2PlayersSumDB::insertGetId([
                    'user_id' => $uid,
                    'date_id' => $r['date_id'],
                    'times' => $r['times'],
                    'game_id' => $req['game_id'],
                    'count' => $req['count'],
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);
            } else {
                $count = Game2PlayersSumDB::where('user_id', $uid)->where('date_id', $r['date_id'])->where('times', $r['times'])->value("count");
                Game2PlayersSumDB::where('user_id', $uid)->where('date_id', $r['date_id'])->where('times', $r['times'])->update([
                    'count' => $count + $req['count'],
                    'updated_at' => Carbon::now()->toDateTimeString()
                ]);
            }
        } else {
            return json([
                'code' => 0,
                'msg' => 'ok',
                'data' => 'U蛋不够',
            ]);
        }
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $doesntExist,
        ]);
    }

    //获取当前游戏
    public function getNowGame()
    {
        $res = Game2DB::orderBy('id', 'desc')->first();
        $res['now_time'] = Carbon::now()->toDateTimeString();
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    //投注列表
    public function playGameList(Request $request)
    {
        $uid = $request->uid;
        $list = Game2PlayersDB::where('user_id', $uid)
           ->leftJoin('game2', 'game2_players.game_id', '=', 'game2.id')
           ->select('game2_players.*', 'game2.open_time')
           ->orderBy('id', 'desc')->paginate(10);
        // $list = Game2PlayersDB::where('user_id', $uid)->orderBy('id', 'desc')->paginate(10);
        // $list['now_time'] = Carbon::now()->toDateTimeString();
        // $list = Game2PlayersSumDB::where('user_id', $uid)->orderBy('id', 'desc')->paginate(10);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'now_time'=>Carbon::now()->toDateTimeString(),
            'data' => $list,
        ]);
    }

    //获取某期号的游戏
    public function getDateIdInfo(Request $request)
    {
        $id = $request->get('id');
        $res = Game2DB::where('id', $id)->first();
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    //开奖
    public function openGame()
    {
        //获取所有牌
        $cards = Game2PukeDB::where('used', 0)->get()->toArray();
        //随机抽走3张
        shuffle($cards);
        $res = array_slice($cards, 0, 3); // 获取前3个元素;
        //数据库中更新状态
        Game2PukeDB::upsert(
            [
                [
                    'id' => $res[0]['id'],
                    'used' => 2
                ],
                [
                    'id' => $res[1]['id'],
                    'used' => 1
                ],
                [
                    'id' => $res[2]['id'],
                    'used' => 1
                ]
            ],
            ['id'],
            ['used']
        );
        //更新游戏记录
        $game = Game2DB::orderBy('id', 'desc')->first();
        Game2DB::where('id', $game['id'])->update([
            'card0' => $res[0]['card'],
            'card0_val' => $res[0]['value'],
            'card0_type' => $res[0]['type'],
            'card1' => $res[1]['card'],
            'card1_val' => $res[1]['value'],
            'card1_type' => $res[1]['type'],
            'card2' => $res[2]['card'],
            'card2_val' => $res[2]['value'],
            'card2_type' => $res[2]['type'],
        ]);
        $list = Game2DB::orderBy('id', 'desc')->first();
        sleep(1);
        $this->updatePrize($game['date_id'], $game['times']);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $list,
        ]);
    }

    //奖励发送
    public function updatePrize($date_id, $times)
    {
        //获取要查询的局次
        $info = Game2DB::where('date_id', $date_id)->where('times', $times)->first();
        $e['A'] = $info['card1_val'];
        $e['B'] = $info['card2_val'];
        //获取当前游戏的所有投注信息
        $e['list'] = Game2PlayersDB::where('date_id', $date_id)->where('times', $times)->get()->toArray();
        //所有投注信息进行中奖信息更新
        $this->userOpenGame($e);
        //更新完之后兑奖
        sleep(1);
        $list = Game2PlayersDB::where('date_id', $date_id)->where('times', $times)->get()->toArray();
        $res = $this->gotPrize($list);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    //中奖更新
    public function userOpenGame($e)
    {
        foreach ($e['list'] as $v) {
            //获取中奖信息
            $info = Game2PlayersDB::where('id', $v['id'])->first();
            $A = $e['A'];
            $B = $e['B'];
            /**
             * AA猫赢  BB狗赢  AB 和局 A猫单赢 B狗单赢   A2猫双赢  B2狗双赢
             */
            switch ($info['type']) {
                case 'AA':
                    if ($A > $B) {
                        Game2PlayersDB::where('id', $v['id'])->update([
                            'is_got' => 1,
                            'price' => $info['rate'] * $info['count'] + $info['count']
                        ]);
                    }
                    if ($A == $B) {
                        Game2PlayersDB::where('id', $v['id'])->update([
                            'is_got' => 1,
                            'price' => $info['rate'] * $info['count'] / 2 
                        ]);
                    }
                    break;
                case 'BB':
                    if ($A < $B) {
                        Game2PlayersDB::where('id', $v['id'])->update([
                            'is_got' => 1,
                            'price' => $info['rate'] * $info['count'] + $info['count']
                        ]);
                    }
                    if ($A == $B) {
                        Game2PlayersDB::where('id', $v['id'])->update([
                            'is_got' => 1,
                            'price' => $info['rate'] * $info['count'] / 2 
                        ]);
                    }
                    break;
                case 'AB':
                    if ($A == $B) {
                        Game2PlayersDB::where('id', $v['id'])->update([
                            'is_got' => 1,
                            'price' => $info['rate'] * $info['count'] + $info['count']
                        ]);
                    }
                    break;
                case 'A':
                    if ($A % 2 == 1) {
                        Game2PlayersDB::where('id', $v['id'])->update([
                            'is_got' => 1,
                            'price' => $info['rate'] * $info['count'] + $info['count']
                        ]);
                    }
                    break;
                case 'B':
                    if ($B % 2 == 1) {
                        Game2PlayersDB::where('id', $v['id'])->update([
                            'is_got' => 1,
                            'price' => $info['rate'] * $info['count'] + $info['count']
                        ]);
                    }
                    break;
                case 'A2':
                    if ($A % 2 == 0) {
                        Game2PlayersDB::where('id', $v['id'])->update([
                            'is_got' => 1,
                            'price' => $info['rate'] * $info['count'] + $info['count']
                        ]);
                    }
                    break;
                case 'B2':
                    if ($B % 2 == 0) {
                        Game2PlayersDB::where('id', $v['id'])->update([
                            'is_got' => 1,
                            'price' => $info['rate'] * $info['count'] + $info['count']
                        ]);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    //兑奖
    public function gotPrize($list)
    {
        foreach ($list as $v) {
            //中奖
            if ($v['is_got'] == 1) {
                //给用户钱包添加中奖金额
                $held_eggs = WalletsDB::where('wallet_user_id', $v['user_id'])->value('held_eggs');
                WalletsDB::where('wallet_user_id', $v['user_id'])->update([
                    'held_eggs' => $v['price'] + $held_eggs
                ]);
                //添加U蛋记录
                EggsDB::insertGetId([
                    'uid' => $v['user_id'],
                    'count' => $v['price'],
                    'type' => '游戏-中奖-猫狗斗' . $v['date_id'] . '-' . $v['times'],
                    'yu_e' => $v['price'] + $held_eggs,
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);
                //添加到聚合表中
                $price = Game2PlayersSumDB::where('user_id', $v['user_id'])->where('date_id', $v['date_id'])->where('times', $v['times'])->value('price');
                Game2PlayersSumDB::where('user_id', $v['user_id'])->where('date_id', $v['date_id'])->where('times', $v['times'])->update([
                    'price' => $price + $v['price']
                ]);
            }
        }
        return $list;
    }
}
